package com.briup.jd2407cms.web.interceptor;

import com.briup.jd2407cms.exception.ServiceException;
import com.briup.jd2407cms.result.Result;
import com.briup.jd2407cms.result.ResultCode;
import com.briup.jd2407cms.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.logging.Handler;

/**
 * @BelongsProject: cms2
 * @BelongsPackage: com.briup.jd2407cms.web.interceptor
 * @Author: wangjie
 * @CreateTime: 2024-11-20  09:02
 * @Description: TODO
 * @Version: 1.0
 */
@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (!(handler instanceof HandlerMethod)){
            return true;
        }
        String token = request.getHeader("Authorization");
        if (token==null){
            throw new RuntimeException("无token，请重新登陆");
        }
        try {
            Claims claims = JwtUtil.parseJWT(token);
            log.info(String.valueOf(claims));
            String userId = claims.get("userId").toString();
            Long id = Long.valueOf (userId);
            log.info("id{}",userId);
            request.setAttribute("userId",userId);
        }catch (ExpiredJwtException e){
            log.error(e.getMessage());
            throw new RuntimeException("登录到期");
        }catch (MalformedJwtException e){
            log.error(e.getMessage());
            throw new RuntimeException("令牌失效");
        }catch (Exception e){
            log.error(e.getMessage());
            throw new ServiceException(ResultCode.SYSTEM_INNER_ERROR);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
